const Service = require('egg').Service;
const HttpException = require('../../exception/http');
class UserService extends Service {
	tableName = 'user-table';
	// 登录
	async login(data) {
		const { ctx, app } = this;
		const { username } = data;

		console.log('=====username=====', username);

		let user = await app.mongo.findOne(this.tableName, { query: { username } });
		console.log('=====user=====', user);
		if (!user && username === 'admin') {
			// 如果admin不存在，插入一条记录
			const createTime = ctx.helper.getCurrentTime();
			const res = await app.mongo.insertOne(this.tableName, {
				doc: { username: 'admin', status: 1, userDesc: '超级管理员', createTime }
			});
			if (res.ops) {
				user = res.ops[0];
			}
		} else if (!user && username !== 'admin') {
			throw new HttpException(403, '用户不存在');
		}
		const token = ctx.helper.generateToken(username);
		return { user, token };
	}
	// 查询
	async queryUser(data = {}) {
		const users = await this.app.mongo.find(this.tableName, {
			query: { ...data }
		});
		if (users && users.length) {
			return users;
		}
		return [];
	}
	// 创建用户
	async createUser(data = {}) {
		const { app, ctx } = this;
		const { username, userDesc, status } = data;
		// 这个要做一个判断
		const createTime = ctx.helper.getCurrentTime();
		const res = await app.mongo.insertOne(this.tableName, {
			doc: { username, status: status ? 1 : 0, userDesc, createTime }
		});
		return res;
	}
	// 更新表
	async updateTable() {}
	// 根据id删除用户
	async deleteUser(id) {
		const { app, ctx } = this;
		const objectId = app.getObjectId(id);
		const user = await app.mongo.findOne(this.tableName, {
			query: { _id: objectId }
		});
		// 判断一下，如果是admin则不允许删除
		if (user && user.username === 'admin') {
			throw new HttpException(403, "超级管理员不能删除");
		}
		const res = await app.mongo.findOneAndDelete(this.tableName, {
			filter: { _id: app.getObjectId(id) }
		});
		return res;
	}
}

module.exports = UserService;
